//
//  LPTTabBarViewController.m
//  LPTClient
//
//  Created by mac on 2018/12/2.
//  Copyright © 2018年 zhaodd. All rights reserved.
//

#import "LPTTabBarViewController.h"
#import "LPTLoginViewController.h"
#import "LPTBaseRequest.h"
#import "AuthenticateAddTableViewController.h"
#import "MMProgressHUD.h"
#import "CustomAlertViewController.h"
#import "ECAddressPresentationController.h"
#import "ECAddressChooseTransitioner.h"

@interface LPTTabBarViewController ()<UITabBarControllerDelegate>

@property (nonatomic, strong) CustomAlertViewController *vc;

@end

@implementation LPTTabBarViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

+(LPTTabBarViewController *)instantiate
{
    LPTTabBarViewController *tabbarVC = [[UIStoryboard storyboardWithName:@"Root" bundle:nil] instantiateInitialViewController];
    return tabbarVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.delegate = self;
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self addBarItems];

    // 发通知： 跳到登录
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentLoginVC:) name:@"auto_present_loginvc" object:nil];
    // 发通知： 刷新用户信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestUserInfo:) name:@"refresh_login_userinfo" object:nil];

    // 弹出登录
    NSString *token = [LTPCacheManager shareInstance].token;
    
    if (!token) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.001 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
            [self presentLoginVC:nil];
            
        });
    } else {
        // 加载用户信息, 先缓存起来
        [self requestUserInfo:nil];
    }

}

-(void)addBarItems
{
    
}

- (void)requestUserInfo:(NSNotification *)notifi
{
    NSString *needLoading = [notifi object];
    if (needLoading && [needLoading integerValue] == 1) {
        [MMProgressHUD show];
    }
    NSString *apiName = @"/api/doctor_info";

    LPTBaseRequest *request = [[LPTBaseRequest alloc] initWithApi:apiName withBody:@{} withMethod:YTKRequestMethodGET];
    
    [request startRequestWithClass:[UserInfoModel class] completeSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        [MMProgressHUD dismiss];
        // 缓存用户信息；
        [[LTPCacheManager shareInstance] cacheUserInfo:request.responseObject[@"data"]];
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        [MMProgressHUD dismiss];
    }];
}

- (void)presentLoginVC:(NSNotification *)notification
{
    [[LTPCacheManager shareInstance] logOut];
    LPTLoginViewController *loginVC = [LPTLoginViewController instance];
    [self presentViewController:loginVC animated:NO completion:^(void){
        [self.tabBarController setSelectedIndex:0];
    }];

}

// 弹出框，提示去认证
- (void)showCentifierVC
{
    if (![LTPCacheManager shareInstance].getUserInfoModel.doctor.credential) {
        // 未审核的
        self.vc = nil;
        self.vc = [CustomAlertViewController instanceWithType:CustomAlertStyleAuthen title:@"立即认证" desc:@"马上拥有属于自己的工作室" Complete:^(BOOL commitBtnClick, BOOL exchangeBtnClick) {
            
            if (commitBtnClick) {
                AuthenticateAddTableViewController *vc = [AuthenticateAddTableViewController instance];
                UINavigationController *viewController = [self.viewControllers firstObject];
                
                if (viewController) {
                    [[viewController topViewController].navigationController pushViewController:vc animated:YES];
                }
            } else if (exchangeBtnClick) {
                // 切换账号
                [self.vc dismissViewControllerAnimated:YES completion:^{
                    [self presentLoginVC:nil];
                }];
            }


        }];
        ECAddressChooseTransitioningDelegate *vcDelete = [[ECAddressChooseTransitioningDelegate alloc] init];
        UINavigationController *viewController = [self.viewControllers firstObject];
        if (viewController) {
            [self.vc setModalPresentationStyle:UIModalPresentationCustom];
            [viewController topViewController].transitioningDelegate = vcDelete;
            self.vc.transitioningDelegate = vcDelete;
            [[viewController topViewController] presentViewController:self.vc animated:YES completion:NULL];
        }
        return;
    }
    UserInfoDetail *userInfoDetail = [LTPCacheManager shareInstance].getUserInfoModel.doctor.credential;
    
    if (userInfoDetail.status == 0) {
        // 审核中
        self.vc = nil;
        self.vc = [CustomAlertViewController instanceWithType:CustomAlertStyleCerting title:@"审核中" desc:@"您提交的资料正在审核中" Complete:^(BOOL commitBtnClick, BOOL exchangeBtnClick)  {
            if (exchangeBtnClick) {
                // 切换账号
                [self.vc dismissViewControllerAnimated:YES completion:^{
                    [self presentLoginVC:nil];
                }];
            }
        }];
        ECAddressChooseTransitioningDelegate *vcDelete = [[ECAddressChooseTransitioningDelegate alloc] init];
        UINavigationController *viewController = [self.viewControllers firstObject];
        if (viewController) {
            [self.vc setModalPresentationStyle:UIModalPresentationCustom];
            [viewController topViewController].transitioningDelegate = vcDelete;
            self.vc.transitioningDelegate = vcDelete;
            [[viewController topViewController] presentViewController:self.vc animated:YES completion:NULL];
        }

    } else if (userInfoDetail.status == 2) {
        // 审核失败
    }
    
}


- (void)showExchangeAccountAlert
{
    UIAlertController *alerVC = [UIAlertController alertControllerWithTitle:@"切换账号" message:@"确定要切换账号吗？" preferredStyle:UIAlertControllerStyleAlert];
    [alerVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alerVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self.navigationController popToRootViewControllerAnimated:NO];
        [[LTPCacheManager shareInstance] logOut];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"auto_present_loginvc" object:nil];
        
    }]];
    [self presentViewController:alerVC animated:YES completion:NULL];
    
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    BOOL isCer = [LTPCacheManager shareInstance].isCertified;
    if (!isCer) {
        [self showCentifierVC];
    }
    return isCer;
}


@end
